package com.sky.exceptionHandler;

import com.sky.constant.ResultCodeConstant;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    private Result ServiceExceptionHandler(ServiceException e) {
        log.error("业务异常=>{}", e.getMessage());
        Integer code = e.getCode();
        return code == null ? Result.error(1, e.getMessage()) : Result.error(code, e.getMessage());
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(JwtException.class)
    private Result JwtExceptionHandler(JwtException e) {
        log.error("权限异常=>{}", e.getMessage());
        Integer code = e.getCode();
        return code == null ? Result.error(ResultCodeConstant.AuthCode, e.getMessage()) : Result.error(code, e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return Result.error(e.getMessage());
    }


    /**
     * 404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFound(NoHandlerFoundException e, HttpServletRequest request) {
        log.error("请求地址'{}',找不到改url.", request.getRequestURI(), e);
        return Result.error(e.getMessage());
    }


}
